﻿using System;
using System.Collections.Generic;
using CodeFirstMVC3.Core;
using CodeFirstMVC3.Core.Validation;
using CodeFirstMVC3.DataAccess.Model;
using CodeFirstMVC3.Domain.DataAccess;
using CodeFirstMVC3.Domain.Model;
using CodeFirstMVC3.Domain.Service;

namespace CodeFirstMVC3.Service
{
    public class UserService : IUserService
    {
        private readonly IRepository<User> _repository;

        public UserService(IRepository<User> repository)
        {
            _repository = repository;
        }

        public IUser New()
        {
            return _repository.NewEntity();
        }

        public void Add(IUser entity)
        {
            _repository.Add(entity as User);
            _repository.Save();
        }

        public void Edit(IUser entity)
        {
            User m = entity as User;
            _repository.Save();
        }

        public void Remove(IUser entity)
        {
            _repository.Remove(entity as User);
            _repository.Save();
        }

        public IUser Get(int id)
        {
            return _repository.Get(p => p.Id == id);
        }

        public IUser Get(Func<IUser, bool> predicate)
        {
            return _repository.Get(predicate);
        }

        public int GetCount(Func<IUser, bool> perdicate = null)
        {
            if (perdicate == null)
                return _repository.GetCount(p => true);
            return _repository.GetCount(perdicate);
        }

        public IEnumerable<IUser> GetAll(Func<IUser, bool> predicate = null, int start = 0, int count = ApplicationSettings.PageSize)
        {
            if (predicate == null)
                return _repository.GetAll(p => true);

            if (start == 0)
            {
                return _repository.GetAll(predicate);
            }

            return _repository.GetAll(predicate, start, count);
        }

        public IEnumerable<IValidationMessage> Validate(IUser entity)
        {
            //TODO
            if (string.IsNullOrEmpty(entity.Firstname))
                yield return new ValidationMessage(MessageType.Error, "First name is required", entity.GetPropertyName(e => e.Firstname));
        }
    }
}
